package org.wat.wcy.isi.mmazur.bp.io.model;

import java.io.RandomAccessFile;
import java.util.Arrays;

import org.wat.wcy.isi.mmazur.bp.io.BinaryObject;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.LoopType;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.MILoopOrderingType;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.TestTimeType;

public class Loop extends BinaryObject {

	private final static int CONDITION_SIZE = 512;

	private LoopType type;
	/**
	 * Only for standard loop
	 */
	private TestTimeType testTime;
	/**
	 * Only for MI loop
	 */
	private MILoopOrderingType miLoopOrdering;
	private int loopCounter;
	private int loopMax;
	private String condition;

	public Loop() {
		type = LoopType.NONE;
		testTime = TestTimeType.NONE;
		condition = "";
		miLoopOrdering = MILoopOrderingType.NONE;
	}

	public MILoopOrderingType getMiLoopOrdering() {
		return miLoopOrdering;
	}

	public void setMiLoopOrdering(MILoopOrderingType miLoopOrdering) {
		this.miLoopOrdering = miLoopOrdering;
	}

	public LoopType getType() {
		return type;
	}

	public void setType(LoopType type) {
		this.type = type;
	}

	public TestTimeType getTestTime() {
		return testTime;
	}

	public void setTestTime(TestTimeType testTime) {
		this.testTime = testTime;
	}

	public int getLoopCounter() {
		return loopCounter;
	}

	public void setLoopCounter(int loopCounter) {
		this.loopCounter = loopCounter;
	}

	public int getLoopMax() {
		return loopMax;
	}

	public void setLoopMax(int loopMax) {
		this.loopMax = loopMax;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	@Override
	public void read(RandomAccessFile raf) {
		try {
			int typeInt = raf.readInt();
			type = LoopType.values()[typeInt];
			int testTimeInt = raf.readInt();
			testTime = TestTimeType.values()[testTimeInt];
			int miLoopOrderingInt = raf.readInt();
			miLoopOrdering = MILoopOrderingType.values()[miLoopOrderingInt ];
			loopCounter = raf.readInt();
			loopMax = raf.readInt();
			byte [] b = new byte[CONDITION_SIZE];
			raf.read(b, 0, CONDITION_SIZE);
			condition = new String(b).trim();
		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	@Override
	public void write(RandomAccessFile raf) {
		try {
			raf.writeInt(type.ordinal());
			raf.writeInt(testTime.ordinal());
			raf.writeInt(miLoopOrdering.ordinal());
			raf.writeInt(loopCounter);
			raf.writeInt(loopMax);
			byte b[] = Arrays.copyOf(condition.getBytes(), CONDITION_SIZE);
			raf.write(b);
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}

	public static int sizeOf() {
		return (int) (Integer.SIZE / 8) * 5 + CONDITION_SIZE;
	}
}
